<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>上传图片</title>
  <style>
    div{
      margin: 10px 0;
    }
  </style>
</head>
<body>
  <!-- 上传图片 -->
  <div>
    <span>上传图片：</span>
    <input type="file" onchange="uploadImg(event)"/>
  </div>
  <!-- 图片URL -->
  <div>
    <span>输入图片URL：</span>
    <input id='imgUrl' type="text" value="" placeholder="请输入图片地址" onkeydown="enterSearch(event)" />
  </div>
  <hr/>
  <img id="img" src="" alt=''/>
  <script>
    function uploadImg(event) {
      // 上传的file对象
      console.log('event:',event);
      console.log('event.target.files[0]:',event.target.files[0]);

      // 读图片
      const reader = new FileReader()
      reader.readAsDataURL(event.target.files[0])
      reader.onload = (e)=>{
        document.getElementById('img').src = e.target.result
      }
    }
    function enterSearch(event) {
      if(event.keyCode === 13){
        console.log(document.getElementById('imgUrl').value);
        const imgUrl = document.getElementById('imgUrl').value
        const image = new Image()
        image.src = imgUrl
        image.setAttribute('crossOrigin', 'Anonymous')
        image.onload = ()=> {
          console.log('图片识别成功');
          document.getElementById('img').src = document.getElementById('imgUrl').value
          // 得到图片的base64编码
          const imgBase64 = getBase64(image)
          // 得到图片的file对象
          const imgfile = botf(imgBase64,'image')
          console.log('imgfile',imgfile);
        }
        image.onerror = ()=>{
          console.log('图片识别失败');
        }

      }
    }
    /**
     * 得到图片的base64编码
     */
    function getBase64(img) {
      const canvas = document.createElement('canvas')
      canvas.width = img.width
      canvas.height = img.height
      const ctx = canvas.getContext('2d')
      ctx.drawImage(img, 0, 0, img.width, img.height)
      const dataURL = canvas.toDataURL()
      console.log('dataURL:',dataURL);
      return dataURL
    }

    /**
     * 得到图片的file对象
     */
    function botf(data, fileName) {
      const dataArr = data.split(',')
      const byteString = atob(dataArr[1])
      const u8Arr = new Uint8Array(byteString.length)
      for (let i = 0; i < byteString.length; i++) {
        u8Arr[i] = byteString.charCodeAt(i)
      }
      const options = {
        type: 'image/jpeg',
        endings: 'native'
      }
      return new File([u8Arr], fileName + '.jpg',options)
    }

    /**
     * 读图片
     */
  </script>
</body>
</html>